<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

use Log;

use App\Models\Record\Send\Sms;

class SmsTpl extends Model
{
    protected $table = 'smstpl';

    //全局配置短信key前缀
    private $config_pre = 'sms_';

    var $returnMsg  = ['code'=>0,'msg'=>'发送成功'];

   	/**
    * 发送短信
    * @param  [type] $phone      [发送的手机号]
    * @param  [type] $serviceName [服务商名]
    * @param  [type] $parmas [发送参数]
    * @param  [type] $ip [ip地址]
    * @return [type]              [description]
    */
    function sendSms($phone,$serviceName,$parmas,$ip){
    	if(!$this->id){
    		$this->returnMsg['code'] = 1;
        	$this->returnMsg['msg'] = '请求失败,稍后重试';
    		Log::error("短信模版尚未获取到实例.");
    		return false;
    	}
    	//服务商方法不存在调用失败,记录日志
    	if(!method_exists($this,$serviceName)){
    		$this->returnMsg['code'] = 1;
        	$this->returnMsg['msg'] = '请求失败,稍后重试';
    		Log::error("模版ID:$this->id.调用不存在的服务商:$serviceName");
    		return false;
    	}
    	return call_user_func(array($this,$serviceName),$phone,$parmas,$ip);
    }

    /**
     * 聚合数据短信发送
     * @param  [type] $phone  [手机号]
     * @param  [type] $parmas [参数]
     * @param  [type] $ip [ip地址]
     * @return [type]         [description]
     */
    function juhe($phone,$url_parmas,$ip){
    	$config_key = $this->config_pre.'account_juhe';
    	$sms_url = 'http://v.juhe.cn/sms/send';
    	$config = new Config();
    	//验证聚合账号是否配置
    	$config = $config->cacheFindByKey($config_key);
    	if(!$config || $config->vue==''){
    		Log::error("sms_account_juhe全局配置key尚未配置");
    		$this->returnMsg['code'] = 1;
        	$this->returnMsg['msg'] = '请求失败,稍后重试';
    		return false;
    	}

    	$smsRecord = new Sms();
        //验证60秒发送间隔时间
        $throttle = $smsRecord->checkThrottle($phone,$this->id);
        if($throttle['code']==1){
        	$this->returnMsg['code'] = 1;
        	$this->returnMsg['msg'] = $throttle['msg'];
            return false;
        }
        //验证每日发送次数
        $dayThrottle = $smsRecord->checkDayThrottle($phone,$this->id);
        if($dayThrottle['code']==1){
            $this->returnMsg['code'] = 1;
        	$this->returnMsg['msg'] = $dayThrottle['msg'];
        	return false;
        }
        //保存发送数据
        $smsRecord->phone = $phone;
       	$smsRecord->content = $this->content;
       	$smsRecord->params = json_encode($url_parmas);
       	$smsRecord->ip = $ip;
       	$smsRecord->tpl_id = $this->id;
       	$smsRecord->createDay = date('Y-m-d');
       	
       	$tpl_value = '';
       	foreach($url_parmas as $key =>$value){
       		$tpl_value.= "&#$key#=$value";
       	}

       	//发送短信请求
        $params = array(
			'key'       => $config->vue, 
			'mobile'    => $phone, 
			'tpl_id'    => $this->serviceId, 
			'tpl_value' => substr($tpl_value, 1),
        );
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        curl_setopt( $ch , CURLOPT_POST , true );
        curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
        curl_setopt( $ch , CURLOPT_URL , $sms_url );
        $response = curl_exec( $ch );
        curl_close( $ch );
        //解析短信返回
        if ($response === FALSE) {
            $smsRecord->errorReason = '聚合短信接口响应失败';
            $smsRecord->status = 1;
            $this->returnMsg['code'] = 1;
        	$this->returnMsg['msg'] = '请求失败,稍后重试';
        }else{
            $result               = json_decode($response,true);
            $error_code           = $result['error_code'];
            $smsRecord->errorCode = $error_code;
            if($error_code != 0){
                $smsRecord->errorReason = $result['reason'];
                $smsRecord->status = 1;
                $this->returnMsg['code'] = 1;
        		$this->returnMsg['msg'] = '请求失败,稍后重试';
            }
        }
        $smsRecord->save();
        return $smsRecord->id;
    }
}
